package com.qf.smsplatform.gateway.thread;

import com.qf.smsplatform.common.constants.ReportStateConstants;
import com.qf.smsplatform.common.constants.SourceType;
import com.qf.smsplatform.common.model.StandardReport;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.gateway.mq.DelayMessagePostProcessor;
import com.qf.smsplatform.gateway.mq.StatQueue;
import com.qf.smsplatform.gateway.netty4.entity.CmppDeliver;
import com.qf.smsplatform.gateway.netty4.entity.ReportMatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;

import static com.qf.smsplatform.gateway.config.RabbitConfig.QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SMS_SEND;

public class SendReportThread implements Runnable{
    private final static Logger log = LoggerFactory.getLogger(SendReportThread.class);

    private AmqpTemplate rabbitTemplate;

    private String pushTopic;
    private String updateTopic;

    private StatQueue statqueue = StatQueue.getInstance();

    public SendReportThread(String pushTopic,String updateTopic,AmqpTemplate rabbitTemplate){
        this.pushTopic = pushTopic;
        this.updateTopic = updateTopic;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void run() {
        while (true) {
            try {
                if (statqueue.size() > 0) {
                    log.info("stat queue size:{}",statqueue.size());
                    CmppDeliver deliver = (CmppDeliver) statqueue.remove();  // 从队列取出deliver对象
                    String str = deliver.getStat();             // 获取到了最终发送的状态
                    long msgid = deliver.getMsg_Id_DELIVRD();   // 最终的msgid运营商信息标号
                    ReportMatch reportMatch = ReportMatch.getInstance();
                    log.info("从REPORT MATCH中取值：{}",msgid);
                    StandardSubmit submit = (StandardSubmit) reportMatch.remove(msgid);  // 取出了submit对象
                    StandardReport report = new StandardReport();         // 创建了report对象（为了发送状态报告）
                    report.setSrcID(submit.getSrcSequenceId());
                    report.setMobile(submit.getDestMobile());
                    if(deliver.getResult() == 0){     // 判断Result == 0,证明短信发送成功,  或者判断Stat == DELIVRD , 也代表短信发送成功
                        // 短信发送成功, 设置发送状态为发送成功
                        report.setState(ReportStateConstants.SUCCESS);
                    }else {
                        report.setState(ReportStateConstants.FAIL);
                        report.setErrorCode(deliver.getStat());
                    }
                    report.setMsgId(String.valueOf(msgid));
                    report.setClientID(submit.getClientID());           // 在封装report对象（却操作，后期补全）
                    // 将sequenceId设置到report中,方便修改日志时,获取到文档id
                    report.setSequenceId(submit.getSequenceId());
                    log.info("send report:{}",report);
                    if(submit.getSource() == SourceType.HTTP) {
                        // 发送状态报告
                        rabbitTemplate.convertAndSend(pushTopic, report);
                    }
                    // 发送更新日志的消息
                    rabbitTemplate.convertAndSend(QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SMS_SEND, report, new DelayMessagePostProcessor(10 * 1000));

                    if(deliver.getResult() == 0) {
                        // TODO  短信发送成功~限流操作,  ----  保存数据到zset
                        // TODO  短信发送成功~扣费操作  ----   将缓存中预扣除的费用扣除，并且修改数据库
                    }else {
                        // TODO  短信发送失败~扣费操作  -----   将缓存中预扣除的费用添加回客户的费用缓存中
                    }
                } else {
                    sleep(2000);
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
                sleep(2000);
            }
        }
    }

    private void sleep(long time){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
}
